import React, { Component, Fragment } from "react";
// antd
import { Table, Button, Col, Pagination, Form, Input, Tag, Spin, Drawer, message} from "antd";
import Action from "@c/buttonAction/Index";
// http
import http from '../../utils/request';
// ansi
import Ansi from "ansi-to-react";



function ListItem(props) {
    return <div><Tag color="blue" style={{ marginTop: "5px"}}>{props.value}</Tag></div>
}

class AnsibleLog extends Component {
    constructor(props){
        super(props);
        this.state = {
            // 表格分页
            total: '',
            page: 1,
            page_number: 10,
            dataSource: [],

            columns: [
                {title: "任务名称", dataIndex: "name", key: "name"},
                {title: "任务主机", dataIndex: "index_id", key: "index_id",
                    render: (text, rowData) => {
                        const listItems = rowData.host.map((item) => 
                                <ListItem key={item.toString()} value={item} />
                        );
                        return (
                            <ul>{listItems}</ul>
                        )
                    }   
                },
                {title: "任务结果", dataIndex: "task_status", key: "task_status",
                    render: (text, rowData) => {
                        var data = ''
                        if(rowData.status === 'failed') {
                            data = <Tag color="#f50">失败</Tag>
                        } else if(rowData.status === 'wait') {
                            data = <Tag color="#2db7f5">运行中</Tag>
                        } else if (rowData.status === 'successful'){
                            data = <Tag color="#87d068">成功</Tag>
                        } else {
                            data = <Tag color="#020202">未知</Tag>
                        }
                        return (
                            <div>{data}</div>
                        )
                    }
                },
                {title: "任务进度", dataIndex: "status", key: "status",
                    render: (text, rowData) => {
                        var data = ''
                        if(rowData.task_status === '0') {
                            data = <Spin />
                        } else {
                            data = '结束'
                        }
                        return (
                            <div>{data}</div>
                        )
                    }     
                },
                {title: "执行用户", dataIndex: "user", key: "user"},
                {title: "开始时间", dataIndex: "start_time", key: "start_time"},
                {title: "结束时间", dataIndex: "end_time", key: "end_time"},
                {title: "详情", dataIndex: "task_detail", key: "task_detail",
                    render: (text, rowData) => {
                        return (
                            <div className="inline-button">
                                <Action>
                                    <Action.Button onClick={() => this.onDetailTaskBtn(rowData)}>详情</Action.Button>
                                </Action>
                            </div>
                        )
                    }              
                }
            ],
            loading: false,
            visible_drawer: false,
            search_name: '',
            task_detail: [],
        }
    }

    componentDidMount() {
        this.loadData()
    }

    loadData = () => {
        this.setState({
            loading: true
        })
        const requestData = {
            'page': this.state.page,
            'limit': this.state.page_number,
            'name__contains': this.state.search_name,
        }

        // 获取分组列表
        http.get('/ansible/log', {params: requestData}).then(response=>{
            console.log(response.data.data.items)
            this.setState({
                dataSource: response.data.data.items,
                total: response.data.data.pages.total,
                loading: false
            })
        }).catch()
    }

    /** 切换每页数量 */
    onChangeSizePage = (page, page_number) => {
        this.setState({
            page: page,
            page_number: page_number,
        }, () => {
            this.loadData()
        })
    }

    /** 云平台搜索 */
    onFinishSearch = (data) => {
        this.setState({
            page: 1,
            search_name: data.name ? data.name : null,
        })
        this.loadData()
    }

    onClose = () => {
        this.setState({
            visible_drawer: false
        })
    }

    onDetailTaskBtn = (rowData) => {
        if (rowData.task_status === '0') {
            message.info('请等待任务执行完毕')
            return ''
        }

        http.get('/ansible/log/' + rowData.id).then(response=> {
            const resp_data = response.data.result

            const task_detail = []

            console.log('resp_data: ', resp_data)

            for(let i = 0; i<resp_data.length; i++) {
                task_detail.push(
                    <p><Ansi >{resp_data[i]}</Ansi></p>
                )
            }

            this.setState({
                task_detail: task_detail,
                visible_drawer: true
            })
        })
    }

    editorDidMount = (editor, monaco) => {
        console.log('editorDidMount', editor, monaco);
        editor.focus();
    }

    onChange = (newValue, e) => {
        console.log('onChange', newValue, e);
    }

    render(){
        const { loading, dataSource, columns, page, total, task_detail, visible_drawer } = this.state

        var myStyle = {margin: '20px'}
        return (
            <Fragment>
                <Form layout="inline" onFinish={this.onFinishSearch}>
                    <Form.Item label="任务名称" name="name">
                        <Input placeholder="请输入任务名称"  />
                    </Form.Item>
                    <Form.Item shouldUpdate={true}>
                        <Button type="primary" htmlType="submit">搜索</Button>
                    </Form.Item>
                </Form>

                <div style={myStyle}></div>
                
                <Table
                    pagination={false} 
                    rowKey="id" 
                    columns={columns} 
                    dataSource={dataSource}
                    loading={loading}
                    scroll={{ y: 500, x: '70vw' }}
                >
                </Table>

                <div style={myStyle}>
                    <Col span={16}>
                        <Pagination
                            onChange={this.onChangeSizePage}
                            current={page}
                            total={total}
                            showSizeChanger
                            showQuickJumper
                            showTotal={total => `Total ${total} items`}
                        />
                    </Col>
                </div>

                <Drawer title="任务执行结果" 
                    placement="right" 
                    onClose={this.onClose} 
                    visible={visible_drawer}
                    width={1000}>
                    <span>{task_detail}</span>
                </Drawer>

            </Fragment>
        )
    }
}
export default AnsibleLog;